package CETranslator

import (
	"bufio"
	"embed"
	"io/fs"
	"log"
	"math"
	"strings"
	"unicode"
)

//go:embed cedict_ts.u8
var CEDictFS embed.FS

type CENode struct {
	TraditionalChinese    string
	SimplifiedChinese     string
	EnglishInterpretation string
	PhoneticNotation      string
}

var hanziNodeMap = genHanziNodeMap()

func genHanziNodeMap() map[string][]*CENode {
	ret := make(map[string][]*CENode)
	file, err := CEDictFS.Open("cedict_ts.u8")
	if err != nil {
		log.Fatal(err)
	}
	defer func(file fs.File) {
		err := file.Close()
		if err != nil {

		}
	}(file)

	sc := bufio.NewScanner(file)
	sc.Buffer([]byte{}, math.MaxInt64)

	for sc.Scan() {
		ss := sc.Text()
		if ss[0] == '#' {
			continue
		}
		// 查找第一个 '/'
		idx := strings.Index(ss, "/")
		if idx == -1 {
			continue
		}
		chineseStr := ss[:idx]
		englishStr := ss[idx+1 : len(ss)-1]
		firstSpacePos := strings.Index(chineseStr, " ")
		if firstSpacePos == -1 {
			continue
		}

		secondSpacePos := strings.Index(chineseStr[firstSpacePos+1:], " ")
		if secondSpacePos == -1 {
			continue
		}
		secondSpacePos += firstSpacePos + 1

		traditionalChinese := chineseStr[:firstSpacePos]
		simplifyChinese := chineseStr[firstSpacePos+1 : secondSpacePos]
		phoneticNotation := chineseStr[secondSpacePos+2 : strings.Index(chineseStr, "]")]
		var tNode = CENode{
			TraditionalChinese:    traditionalChinese,
			SimplifiedChinese:     simplifyChinese,
			EnglishInterpretation: englishStr,
			PhoneticNotation:      phoneticNotation,
		}

		for _, chCharacter := range simplifyChinese {
			if !unicode.Is(unicode.Han, chCharacter) {
				continue
			}
			list, ok := ret[string(chCharacter)]
			if !ok {
				list = []*CENode{}
			}
			list = append(list, &tNode)
			ret[string(chCharacter)] = list
		}
	}

	return ret
}
